<?php
namespace Common\Model;

class InvestorQuestionModel extends \Think\Model
{
	//自动验证
	protected $_validate = array(
			//新增
			array('user_id', '/^\d+$/', '请传入用户ID', self::MUST_VALIDATE, 'regex', self::MODEL_INSERT),
			array('mobile', '/^1\d{10}$/', '请传入用户手机号', self::MUST_VALIDATE, 'regex', self::MODEL_INSERT),
			array('fund_id', '/^\d+$/', '请传入基金ID', self::MUST_VALIDATE, 'regex', self::MODEL_INSERT),
			array('question', 'require', '请传入问题', self::MUST_VALIDATE, 'regex', self::MODEL_INSERT),
	);
	
	//自动完成
	protected $_auto = array(
			array('create_time', NOW_TIME, self::MODEL_INSERT, 'string'),
			array('update_time', NOW_TIME, self::MODEL_BOTH, 'string'),
			array('status', 2, self::MODEL_INSERT, 'string'),
	);
	
	/**
	 * 添加提问
	 */
	public function addQuestion($data)
	{
		if(!$this->create($data)) return array('error' => 1, 'info' => $this->getError());
		
		//查询指定的基金是否存在
		$fund = M('Invest')->where(array('status' => 1, 'id' => $this->fund_id))->find();
		if(!$fund) array('error' => 1, 'info' => '要提问的基金不存在');
		
		$id = $this->add();
		
		if($id) return array('error' => 0, 'info' => '添加成功');
		
		//测试代码
		//return array('error' => 1, 'info' => $this->getError());
		
		return array('error' => 1, 'info' => '添加失败');
	}
	
	/**
	 * 查询投资人疑问
	 * @param array $where
	 * @param array $option
	 * @param string $order
	 * @return maxied
	 */
	public function searchQuestion($where = array(), $option = array(), $order = 'create_time desc')
	{
		if($option) {
			if($option['page'] && $option['size']) {
				$page = $option['page'];
				$size = $option['size'];
				$this->page($page, $size);
			} 
		}

		//查询问题
		$field = 'id,user_id,mobile,fund_id,question,create_time,status';
		if($where ) $this->where($where);
		$question = $this->field($field)->order($order)->select();
		
		//查询回答
		if($question) {
			$ids = array();
			foreach($question as &$q) {
				$ids[] = $q['id'];
				$q['answer'] = '';
				$q['answer_time'] = '';
			}
			
			$answer = M('InvestorQuestionAnswer')->where(array('status'=>1, 'id'=>array('in', $ids)))->select();
			if($answer) {
				foreach($answer as $a) {
					foreach($question as &$q) {
						if($a['question_id'] === $q['id']) {
							$q['answer'] = $a['answer'];
							$q['answer_time'] = $a['create_time'];
						}
					}
				}
			}
		}
		
		return $question;
	}
}